/* components */
import { 
  BaseSelectUserFilterRole, 
  BaseSelectUserFilterButton, 
  BaseSelectUserFilterDepartment, 
  BaseSelectUserFilterServiceProvider,
  BaseSelectUserFilterCustom,
} from '@src/component/common/BaseSelectUser/components'
/* enum */
import { BaseSelectUserComponentNameEnum, BaseSelectUserFetchDebounceTime } from '@src/component/common/BaseSelectUser/model'
/* hooks */
/* store */
import { useBaseSelectUserStore } from '@src/component/common/BaseSelectUser/store/hooks/base'
import { BaseSelectUserVuexPropertyEnum } from '@src/component/common/BaseSelectUser/store'
import { 
  useBaseSelectUserStoreCurrentDepartmentNav,
  useBaseSelectUserStoreCurrentServiceProviderNav,
  useBaseSelectUserStoreCurrentTabType, 
  useBaseSelectUserStoreCurrentToggleRole,
  useBaseSelectUserStoreCurrentToggleServiceProvider, 
  useBaseSelectUserStoreDepartmentData, 
  useBaseSelectUserStoreDepartmentNavList, 
  useBaseSelectUserStoreFilterForm, 
  useBaseSelectUserStoreFilterNeedUpdateMap, 
  useBaseSelectUserStoreIsFilterVisible, 
  useBaseSelectUserStoreUserCountMap,
  useBaseSelectUserStoreUserListMap,
} from '@src/component/common/BaseSelectUser/store'
import { 
  useFetchDepartmentList, 
  useFetchRoleList, 
  useFetchServiceProviderList, 
  useBaseSelectUserFilterForm, 
  useBaseSelectUserFilterCount, 
  useBaseSelectUserDepartmentListParams,
  useBaseSelectUserRoleUserListParams,
  useBaseSelectUserServiceProviderUserListParams,
  useBaseSelectUserDepartmentUserListParams,
  useFetchDepartmentUserList,
  useFetchRoleUserList,
  useFetchServiceProviderUserList,
  useBaseSelectUserFilter,
  useFetchRoleListAndRoleUserList,
  useFetchServiceProviderListAndServiceProviderUserList,
  useFetchDepartmentListAndDepartmentUserList
} from '@src/component/common/BaseSelectUser/hooks'
import { useBaseSelectUserOptions } from '@src/component/common/BaseSelectUser/hooks/options'
/* model */
import { BaseSelectUserErrorMessageEnum } from '@src/component/common/BaseSelectUser/model'
/* scss */
import '@src/component/common/BaseSelectUser/components/Filter/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, Ref, ref, watch } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* types */
import { 
  BaseSelectUserFilterRoleForm, 
  BaseSelectUserFilterDepartmentForm, 
  BaseSelectUserFilterServiceProviderForm 
} from '@src/component/common/BaseSelectUser/types'
/* util */
import { debounce } from 'lodash'
import { isEmpty, isFalse, isNotEmpty, isNotEqual } from '@src/util/type'

export type FilterProps = {
  
}

export interface FilterSetupState {
  
}

export enum FilterEmitEventNameEnum {
  Input = 'input',
}

export type FilterInstance = ComponentInstance & FilterSetupState
export type FilterVM = ComponentRenderProxy<FilterProps> & CommonComponentInstance & FilterInstance

export default defineComponent({
  name: BaseSelectUserComponentNameEnum.BaseSelectUserFilter,
  emits: [
    FilterEmitEventNameEnum.Input
  ],
  props: {
    
  },
  setup(props: FilterProps, { emit }) {
    
    const popoverElement: Ref<any> = ref(null)
    const isPopoverButtonClickOpen = ref(true)
    
    const { 
      filterRoleForm, filterDepartmentForm, filterServiceProviderForm,
      setFilterDepartmentForm, setFilterRoleForm, setFilterServiceProviderForm,
    } = useBaseSelectUserStoreFilterForm()
    
    const { setDepartmentList } = useBaseSelectUserStoreDepartmentData()
    const { setDepartmentUserList, setRoleUserList, setServiceProviderUserList } = useBaseSelectUserStoreUserListMap()
    
    const { initFilterDepartmentForm, initFilterRoleForm, initFilterServiceProviderForm } = useBaseSelectUserFilterForm()
    
    const { isFetchDepartmentRootList, isFetchServiceProviderList, isFetchRoleList } = useBaseSelectUserFilter()
    
    const fetchDepartmentList = useFetchDepartmentList()
    const fetchDepartmentUserList = useFetchDepartmentUserList()
    const fetchDepartmentListAndDepartmentUserList = useFetchDepartmentListAndDepartmentUserList()
    const fetchRoleList = useFetchRoleList()
    const fetchRoleListAndRoleUserList = useFetchRoleListAndRoleUserList()
    const fetchRoleUserList = useFetchRoleUserList()
    const fetchServiceProviderList = useFetchServiceProviderList()
    const fetchServiceProviderUserList = useFetchServiceProviderUserList()
    const fetchServiceProviderListAndServiceProviderUserList = useFetchServiceProviderListAndServiceProviderUserList()
    
    const { isCurrentToggleRoleEmpty, setCurrentToggleRole } = useBaseSelectUserStoreCurrentToggleRole()
    const { isCurrentServiceProviderNavEmpty, setCurrentServiceProviderNav } = useBaseSelectUserStoreCurrentServiceProviderNav()
    const { setDepartmentNavList, isDepartmentNavListEmpty } = useBaseSelectUserStoreDepartmentNavList()
    const { currentDepartmentNav } = useBaseSelectUserStoreCurrentDepartmentNav()
    
    const { setDepartmentRootList } = useBaseSelectUserStoreDepartmentData()
    const { setDepartmentRootUserList } = useBaseSelectUserStoreUserListMap()
    const { setDepartmentRootUserCount } = useBaseSelectUserStoreUserCountMap()
    
    const { resetPageNum: resetDepartmentListPageNum } = useBaseSelectUserDepartmentListParams()
    const { resetPageNum: resetDepartmentUserListPageNum } = useBaseSelectUserDepartmentUserListParams()
    const { resetPageNum: resetRoleUserListPageNum } = useBaseSelectUserRoleUserListParams()
    const { resetPageNum: resetServiceProviderUserListPageNum } = useBaseSelectUserServiceProviderUserListParams()
    
    const { currentFilterFormCount } = useBaseSelectUserFilterCount()
    const { isDepartmentTab, isRoleTab, isServiceProviderTab } = useBaseSelectUserStoreCurrentTabType()
    
    const { 
      setFilterNeedUpdateMapDepartment, 
      setFilterNeedUpdateMapRole, 
      setFilterNeedUpdateMapServiceProvider 
    } = useBaseSelectUserStoreFilterNeedUpdateMap()
    
    const { isFilterVisible, setIsFilterVisible } = useBaseSelectUserStoreIsFilterVisible()
    
    const roleForm = ref(filterRoleForm.value)
    const departmentForm = ref(filterDepartmentForm.value)
    const serviceProviderForm = ref(filterServiceProviderForm.value)
    const ContentForm = ref(filterServiceProviderForm.value)
    const visible = ref(false)
    
    const clearRootDepartmentAndUserList = () => {
      setDepartmentRootUserList()
      setDepartmentRootUserCount()
    }
    
    const clearDepartmentAndUserList = () => {
      setDepartmentList([])
      setDepartmentUserList()
    }
    
    const clearRoleUserList = () => {
      setRoleUserList()
    }
    
    const clearServiceProviderUserList = () => {
      setServiceProviderUserList()
    }
    
    const onPopoverButtonClick = () => {
      isPopoverButtonClickOpen.value = !isPopoverButtonClickOpen.value
      visible.value = true
    }
    watch(
      visible, 
      (value) => {
        setIsFilterVisible(value)
      }, 
      { immediate: true }
    )

    const { isScreenSelect, isRenderFilterContent, renderFilterContent } = useBaseSelectUserOptions()
    return {
      visible,
      popoverElement,
      currentFilterFormCount,
      currentDepartmentNav,
      
      filterDepartmentForm,
      filterRoleForm,
      filterServiceProviderForm,
      
      departmentForm,
      roleForm,
      serviceProviderForm,
      ContentForm,
      
      isDepartmentTab,
      isRoleTab,
      isServiceProviderTab,
      isPopoverButtonClickOpen,
      isDepartmentNavListEmpty,
      isCurrentToggleRoleEmpty,
      isCurrentServiceProviderNavEmpty,
      isFilterVisible,
      
      isFetchDepartmentRootList,
      isFetchServiceProviderList,
      isFetchRoleList,
      
      clearRootDepartmentAndUserList,
      clearDepartmentAndUserList,
      clearRoleUserList,
      clearServiceProviderUserList,
      
      onPopoverButtonClick,
      
      resetDepartmentListPageNum,
      resetDepartmentUserListPageNum,
      resetRoleUserListPageNum,
      resetServiceProviderUserListPageNum,
      
      initFilterDepartmentForm,
      initFilterRoleForm,
      initFilterServiceProviderForm,
      
      setDepartmentRootList,
      setDepartmentRootUserList,
      setDepartmentRootUserCount,
      
      setFilterDepartmentForm,
      setFilterRoleForm,
      setFilterServiceProviderForm,
      
      setCurrentToggleRole,
      setCurrentServiceProviderNav,
      
      setDepartmentNavList,
      
      fetchDepartmentList,
      fetchDepartmentListAndDepartmentUserList,
      fetchRoleList,
      fetchServiceProviderList,
      fetchDepartmentUserList,
      fetchRoleUserList,
      fetchRoleListAndRoleUserList,
      fetchServiceProviderUserList,
      fetchServiceProviderListAndServiceProviderUserList,
      
      setFilterNeedUpdateMapDepartment, 
      setFilterNeedUpdateMapRole, 
      setFilterNeedUpdateMapServiceProvider,

      isScreenSelect,
      isRenderFilterContent,
      renderFilterContent,
    }
  },
  watch: {
    currentTabType(newValue) {
      
      if (this.isDepartmentTab) {
        this.departmentForm = this.filterDepartmentForm
      }
      
      if (this.isRoleTab) {
        this.roleForm = this.filterRoleForm
      }
      
      if (this.isServiceProviderTab) {
        this.serviceProviderForm = this.filterServiceProviderForm
      }
      
    },
    isFilterVisible(newValue) {
      if (isFalse(newValue)) {
        this.closePopper()
      }
    }
  },
  methods: {
    close() {
      
      if (isFalse(this.isPopoverButtonClickOpen)) {
        this.confirm()
        this.isPopoverButtonClickOpen = true
      }
      
      this.closePopper()
      
    },
    closePopper() {
      this.visible = false
      this.popoverElement.showPopper = false
    },
    reset() {
      if (this.isDepartmentTab) {
        this.resetWithDepartment()
      }
      
      if (this.isRoleTab) {
        this.resetWithRole()
      }
      
      if (this.isServiceProviderTab) {
        this.resetWithServiceProvider()
      }
    },
    resetWithDepartment() {
      // 清空筛选表单数据
      this.initFilterDepartmentForm()
      
      const isFetchRoot = isNotEmpty(this.departmentForm.tagName) && isEmpty(this.filterDepartmentForm.tagName)
      
      this.departmentForm = this.filterDepartmentForm
      
      this.setFilterNeedUpdateMapDepartment(true)
      
      // 筛选获取数据
      this.fetchDepartmentOrDepartmentUserList(isFetchRoot)
    },
    resetWithRole() {
      
      // 清空筛选表单数据
      this.initFilterRoleForm()
      
      const isFetchRoot = isNotEmpty(this.roleForm.roleName) && isEmpty(this.filterRoleForm.roleName)
      
      this.roleForm = this.filterRoleForm
      
      this.setFilterNeedUpdateMapRole(true)
      
      // 筛选获取数据
      this.fetchRoleOrRoleUserList(isFetchRoot)
    },
    resetWithServiceProvider() {
      // 清空筛选表单数据
      this.initFilterServiceProviderForm()
      
      const isFetchRoot = (
        isNotEmpty(this.serviceProviderForm.spList)
        || isNotEmpty(this.serviceProviderForm.spTypeList)
      )
      
      this.setFilterNeedUpdateMapServiceProvider(true)
      
      this.serviceProviderForm = this.filterServiceProviderForm
      
      // 筛选获取数据
      this.fetchServiceProviderOrServiceProviderUserList(isFetchRoot)
    },
    confirm() {
      
      if (this.isDepartmentTab) {
        this.confirmWithDepartment()
      }
      
      if (this.isRoleTab) {
        this.confirmWithRole()
      }
      
      if (this.isServiceProviderTab) {
        this.confirmWithServiceProvider()
      }
      
    },
    confirmDebounceImplHandler: debounce(function() {
        // @ts-ignore
        this.confirm()
      },
      BaseSelectUserFetchDebounceTime
    ),
    confirmCommon() {
      this.close()
    },
    confirmWithDepartment() {
      
      const isFetchRoot = isNotEqual(this.departmentForm.tagName, this.filterDepartmentForm.tagName)
      const isFetchUser = isEmpty(this.departmentForm.tagName)
      
      // 设置筛选表单数据
      this.setFilterDepartmentForm(this.departmentForm)
      
      this.setFilterNeedUpdateMapDepartment(true)
      
      // 筛选获取数据
      this.fetchDepartmentOrDepartmentUserList(isFetchRoot, isFetchUser)
      
    },
    confirmWithRole() {
      
      const isFetchRoot = isNotEqual(this.roleForm.roleName, this.filterRoleForm.roleName)
      
      // 设置筛选表单数据
      this.setFilterRoleForm(this.roleForm)
      
      this.setFilterNeedUpdateMapRole(true)
      
      // 筛选获取数据
      this.fetchRoleOrRoleUserList(isFetchRoot)
      
    },
    confirmWithServiceProvider() {
      
      const isFetchRoot = (
        isNotEqual(this.serviceProviderForm.spList, this.filterServiceProviderForm.spList)
        || isNotEqual(this.serviceProviderForm.spTypeList, this.filterServiceProviderForm.spTypeList)
      )
      
      this.setFilterNeedUpdateMapServiceProvider(true)
      
      // 设置筛选表单数据
      this.setFilterServiceProviderForm(this.serviceProviderForm)
      
      // 筛选获取数据
      this.fetchServiceProviderOrServiceProviderUserList(isFetchRoot)
      
    },
    fetchDepartmentOrDepartmentUserList(isFetchRoot: boolean = false, isFetchUser: boolean = true) {
      
      // 导航列表为空，表示当前处于根部门列表。需要获取部门列表数据
      if (this.isDepartmentNavListEmpty || isFetchRoot) {
        // 清除当前部门导航，使其回到部门列表
        this.setDepartmentNavList()
        // 重置人员列表
        this.setDepartmentRootList()
        this.setDepartmentRootUserList()
        this.setDepartmentRootUserCount()
        this.clearRootDepartmentAndUserList()
        // 重置分页数
        this.resetDepartmentListPageNum()
        this.resetDepartmentUserListPageNum()
        // 获取部门列表数据
        this.fetchDepartmentListAndDepartmentUserList(isFetchRoot)
        return
      }
      
      // 导航列表不为空，表示当前处于子部门列表。需要获取子部门列表数据
      this.clearDepartmentAndUserList()
      this.resetDepartmentUserListPageNum()
      this.fetchDepartmentListAndDepartmentUserList(false)
      
    },
    fetchRoleOrRoleUserList(isFetchRoot: boolean = false) {
      
      // 当前展开的角色为空，表示当前处于根角色列表。需要获取角色列表数据
      if (this.isCurrentToggleRoleEmpty || isFetchRoot) {
        // 清除当前展开的角色，使其回到角色列表
        this.setCurrentToggleRole()
        // 重置分页数
        this.resetRoleUserListPageNum()
        // 获取角色列表和角色人员数据
        this.fetchRoleListAndRoleUserList(isFetchRoot)
        return
      }
      
      // 当前展开的角色不为空。需要获取角色人员列表数据
      // 重置分页数
      this.resetRoleUserListPageNum()
      this.clearRoleUserList()
      this.fetchRoleListAndRoleUserList(false)
      
    },
    fetchServiceProviderOrServiceProviderUserList(isFetchRoot: boolean = false) {
      
      // 当前展开的服务商为空，表示当前处于根服务商列表。需要获取服务商列表数据
      if (this.isCurrentServiceProviderNavEmpty || isFetchRoot) {
        // 清除当前展开的服务商，使其回到服务商列表
        this.setCurrentServiceProviderNav()
        // 重置分页数
        this.resetServiceProviderUserListPageNum()
        // 获取服务商列表和服务商人员数据
        this.fetchServiceProviderListAndServiceProviderUserList(isFetchRoot)
        return
      }
      
      // 当前展开的服务商不为空。需要获取服务商人员列表数据
      // 重置分页数
      this.resetServiceProviderUserListPageNum()
      // 清除获取服务商人员列表数据
      this.clearServiceProviderUserList()
      // 获取服务商人员列表数据
      this.fetchServiceProviderListAndServiceProviderUserList(false)
      
    },
    onEnterHandler() {
      this.confirm()
      this.close()
    },
    onDepartmentFormChangeHandler(value: BaseSelectUserFilterDepartmentForm) {
      this.departmentForm = value
      this.confirmDebounceImplHandler()
    },
    onRoleFormChangeHandler(value: BaseSelectUserFilterRoleForm) {
      this.roleForm = value
      this.confirmDebounceImplHandler()
    },
    onServiceProviderFormChangeHandler(value: BaseSelectUserFilterServiceProviderForm) {
      this.serviceProviderForm = value
      this.confirmDebounceImplHandler()
    },
    onServiceCustomFormChangeHandler(value: BaseSelectUserFilterServiceProviderForm) {
      this.ContentForm = value
      const store = useBaseSelectUserStore()
      store.commit(BaseSelectUserVuexPropertyEnum.SetSearchCustomOptions, value)
    },
  },
  render(h: CreateElement) {
    return (
      <div class={BaseSelectUserComponentNameEnum.BaseSelectUserFilter}>
        
        <el-popover
          popper-class="base-select-user-filter-popover"
          placement="bottom"
          width="200"
          trigger="click"
          ref="popoverElement"
          onHide={this.close}
        >
          
          <div slot="reference" onClick={this.onPopoverButtonClick}>
            {/* 兼容老数据，只有指定是false才不会展示筛选 */}
            {!(this.isScreenSelect === false) && (<BaseSelectUserFilterButton 
              count={this.currentFilterFormCount} 
              onClose={this.reset}
            />)
            }
          </div>
          
          <div class="base-select-user-filter-popover-content">
            
            {this.isDepartmentTab && (
              <BaseSelectUserFilterDepartment 
                value={this.departmentForm}
                onInput={this.onDepartmentFormChangeHandler}
                onEnter={this.onEnterHandler}
              />
            )}
            
            {this.isRoleTab && (
              <BaseSelectUserFilterRole 
                value={this.roleForm}
                onInput={this.onRoleFormChangeHandler}
                onEnter={this.onEnterHandler}
              />
            )}
            
            {this.isServiceProviderTab && (
              <BaseSelectUserFilterServiceProvider 
                value={this.serviceProviderForm}
                onInput={this.onServiceProviderFormChangeHandler}
                onEnter={this.onEnterHandler}
              />
            )}

            {this.isRenderFilterContent && (
              <BaseSelectUserFilterCustom 
                value={this.ContentForm}
                onInput={this.onServiceCustomFormChangeHandler}
                onEnter={this.onEnterHandler}
              />
            )}
            
          </div>
          
        </el-popover>
        
      </div>
    )
  }
})
